
#ifndef MODBUS_H

#define MODBUS_H

#define read_coils 1

#define write_single_coil 5

#define write_coils 15

#define read_register 3

#define write_register 6

#define write_registers 0x16

#define read_register_response 33

#include "dataDef.h"

typedef struct
{
	unsigned char   			slaveAddress;
	unsigned char   			op;
} mbHeader;

typedef union
{

	struct
	{
		sWord startWord;
		sWord numWord;
		sWord CRC;

	} readPacketRequest;

	struct
	{
		unsigned char byteNum;
		sWord * data;
		sWord CRC;
	} readPacketResponse;

	struct
	{
		sWord startWord;
		sWord data;
		sWord CRC;
	} writeSingleRegRequest;

	struct
	{
		sWord startWord;
		sWord numWord;
		unsigned char byteNum;
		sWord * data;
		sWord CRC;
	} writePacketRequest;

	struct
	{
		sWord startWord;
		sWord numWord;
		sWord CRC;
	} writePacketResponse;

} mbTail;

typedef struct
{
	mbHeader header;
	mbTail tail;
} mbPacket;

unsigned short crc16( unsigned char * pucFrame, unsigned short usLen );

unsigned short calculateMBcrc (mbPacket packet, int type,int lenght);

unsigned char * serializeMBpacket(mbPacket packet, unsigned char * buffer);

mbPacket deserializeMBpacket(unsigned char * buffer);

void reverseWord(sWord * a);

int validateData(unsigned char * buffer);

int receiveData(unsigned char * buffer, int len);

int expectedLenght(mbPacket packet,int type);

#endif
